package org.jdcenter.jndi.context;

import javax.naming.Name;
import javax.naming.NamingException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;



public class JDSContext extends ContextAdapter{
	
	private Log log = LogFactory.getLog(getClass());
	
	public JDSContext(){
		super();
	}
	public JDSContext(String namespace){
		super(namespace);
	}
	public JDSContext(Name name,ContextAdapter previous_context){
		super(name,previous_context);
	}
	
	public void bind(Name name, Object obj) throws NamingException {
		log.debug("name size: "+name.size());
		String nameStr = name.get(posn+1);
        if(name.size() <= posn+2){
        	
        	if(!objects.containsKey(nameStr)){
        		objects.put(nameStr, obj);
        		return;
        	}
        	throw new NamingException("name:"+name.toString()+" is already exist");
        }else{
        	ContextAdapter context = contexts.get(nameStr);
        	if(context == null){
        		context = new JDSContext(name,this);
        		contexts.put(nameStr, context);
        	}
        	context.bind(name, obj);       	
        }
    }
    
    public void rebind(Name name, Object obj) throws NamingException {
        unbind(name);
        bind(name,obj);
    }
    
    public void unbind(Name name) throws NamingException {
    	String nameStr = name.get(posn+1);
        if(name.size() <= posn+2){
        	objects.remove(nameStr);
        }else{
        	ContextAdapter context = contexts.get(nameStr);
        	if(context != null){
        		context.unbind(name);
        	}
        }
    }
    
    public Object lookup(Name name) throws NamingException {
    	String nameStr = name.get(posn+1);
        if(name.size() <= posn+2){
        	return objects.get(nameStr);
        }else{
        	ContextAdapter context = contexts.get(nameStr);
        	if(context == null){
        		return null;
        	}else{
        		return context.lookup(name);
        	}
        }
    }
    
    public void close() throws NamingException {
        // do nothing
    }

}
